#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
from rich.console import Console

console = Console()
if getattr(sys, 'frozen', False):
    # If the application is run as a bundle, the PyInstaller bootloader
    # extends the sys module by a flag frozen=True and sets the app
    current_directory = os.path.dirname(sys.executable)
else:
    # The application is not run as a bundle, so we use the __file__ attribute
    # __file__ is the full path to the module file
    current_directory = os.path.dirname(os.path.abspath(__file__))

# 1. 获取当前用户
current_user = os.getenv("USER")
# 2. 获取当前用户的家目录
home_directory = os.path.expanduser("~")
# 3. 获取当前环境变量文件的配置
environment_file = os.path.join(home_directory, ".bashrc")
try:
    with open(environment_file, "r") as f:
        environment_variables = f.readlines()
except FileNotFoundError:
    environment_variables = []

if not os.getenv("LD_LIBRARY_PATH"):
    if f"export LD_LIBRARY_PATH={current_directory}/dpi:$LD_LIBRARY_PATH" not in environment_variables:
        try:
            with open(environment_file, "a") as f:
                f.write(f"export LD_LIBRARY_PATH={current_directory}/dpi:$LD_LIBRARY_PATH\n")
            console.print(
                "Please execute the following command first: 'source ~/.bashrc' to take effect", style="bold red"
            )
            console.print(
                "Re perform database login operation", style="bold red"
            )
            sys.exit(1)
        except FileNotFoundError:
            console.print(
                f"Please execute the following command first: 'export LD_LIBRARY_PATH={current_directory}/dpi:$LD_LIBRARY_PATH'",
                style="bold red"
            )
    else:
        console.print(
            f"Please execute the following command first: 'export LD_LIBRARY_PATH={current_directory}/dpi:$LD_LIBRARY_PATH'"
        )
